import Response from '../../utils/response.js';
import { shjApi } from '../../utils/request.js';

// 获取内涝列表
export const getList = async (ctx) => {
  try {
    // 创建参数对象
    const params = new URLSearchParams();
    
    const isTotal = ctx.request.body.isTotal;
    const queryName = ctx.request.body.name;
    const queryArea = ctx.request.body.area;
    const queryTown = ctx.request.body.town;
    const querySource = ctx.request.body.source;
    
    if (queryName) {
      params.append('stnmcd', queryName);
    }

    if (queryArea) {
      params.append('addvcd', queryArea);
    }

    if (queryTown) {
      params.append('zhencodes', queryTown);
    }

    if (querySource) {
      params.append('stsys', querySource);
    }

    const response = await shjApi.post('/shuihuanjing/ac/surdep/list', params, {
      headers: {
        token: ctx.headers.token
      }
    });
    
    if (response) {
        const { code, data } = response.data || {}
        const list = data || []
        const totalCount = list.length || 0
        
        if (code == '0000') {
          const statusCount = {
            '全部': totalCount,
            '水位正常': 0,
            '水位延迟': 0,
            '水位离线': 0,
            '水位缺失': 0,
            '视频全部在线': 0,
            '视频部分在线': 0,
            '视频全部离线': 0,
            '视频缺失': 0
          };

          const statusCount_inventory = {
            '全部': totalCount,
            '水位正常': 0,
            '水位延迟': 0,
            '水位离线': 0,
            '水位缺失': 0,
            '视频全部在线': 0,
            '视频部分在线': 0,
            '视频全部离线': 0,
            '视频缺失': 0
          };
          
          const mappedList = list.map(item => {
            const dataMonitorTime = item.zTm;
            const stsysVal = item.stsys
            const isDevice = stsysVal === '物联网平台' || stsysVal === '水务工程监测设施建设项目'

            if (!isDevice) {
              statusCount_inventory['全部'] += 1
            }

            // 获取当前时间（使用本地时区）
            const now = new Date();
            // 设置状态
            let status;

            try {
              if (dataMonitorTime === null || dataMonitorTime === '' || dataMonitorTime === undefined) {
                status = '水位缺失';
              } else {
                const monitorTime = dataMonitorTime ? new Date(dataMonitorTime.replace(/-/g, '/')) : new Date();
                // 计算时间差（毫秒）
                const timeDiff = Math.abs(now.getTime() - monitorTime.getTime());

                if (timeDiff <= 12 *60 * 60 * 1000) { // 12小时以内
                  status = '水位正常';
                } else if (timeDiff > 12 * 60 * 60 * 1000) { // 12小时以上
                  status = '水位延迟';
                } else if (timeDiff > 24 * 60 * 60 * 1000) { // 24小时以上
                  status = '水位离线';
                } 
              }

              if (item.videoDetail) {
                item['__custom_videoDetail'] = JSON.parse(item.videoDetail)
                const onArr = item['__custom_videoDetail'].filter(child => child['STATUS'] === 'ON') || []
                const offArr = item['__custom_videoDetail'].filter(child => child['STATUS'] === 'OFF') || []
                
                if (onArr.length === item['__custom_videoDetail'].length) {
                  item['__custom_videoDetailStatus'] = '视频全部在线'
                } else if (offArr.length === item['__custom_videoDetail'].length) {
                  item['__custom_videoDetailStatus'] = '视频全部离线'
                } else {
                  item['__custom_videoDetailStatus'] = '视频部分在线'
                }
              } else {
                item['__custom_videoDetail'] = null
                item['__custom_videoDetailStatus'] = '视频缺失'
              }
            } catch (error) {
              console.error('解析时间错误:', error);
            }

            // 更新状态计数
            statusCount[status] = (statusCount[status] || 0) + 1;
            statusCount[item['__custom_videoDetailStatus']] = (statusCount[item['__custom_videoDetailStatus']] || 0) + 1;

            if (!isDevice) {
              statusCount_inventory[status] = (statusCount_inventory[status] || 0) + 1;
              statusCount_inventory[item['__custom_videoDetailStatus']] = (statusCount_inventory[item['__custom_videoDetailStatus']] || 0) + 1;
            }

            return {
              ...item,
              status
            };
          });

          const resObj = { statusCount, statusCount_inventory }
          
          if (isTotal == '0') {
            resObj.list = mappedList
          }

          ctx.body = Response.success(resObj)
        } else {
          ctx.body = Response.error('获取数据失败')
        }
    } else {
      console.error('获取数据失败:');
      ctx.body = Response.error('获取数据失败');
    }
  } catch (err) {
    console.error('请求失败:', err);
    ctx.body = Response.error('获取数据失败')
  }
};
